 

package com.zdkj.subway.rca.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.subway.rca.entity.SwCkClearDetail;
import com.zdkj.subway.rca.enums.SwCkClearRuleConstans;
import com.zdkj.subway.rca.service.SwCkClearDetailService;
import com.zdkj.subway.rca.service.SwCkClearRulesService;
import com.zdkj.subway.rca.util.MyDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 清分及划账-清分及划账记录-正常清分数据
 *
 * @author stw
 * @date 2020-11-30 18:52:08
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swckcleardetail" )
@Api(value = "swckcleardetail", tags = "清分及划账-清分及划账记录-正常清分数据")
public class SwCkClearDetailController {

    @Autowired
    private final SwCkClearDetailService swCkClearDetailService;
    @Autowired
    private SwCkClearRulesService swCkClearRuleService;
    /**
     * 分页查询
     * @param page 分页对象
     * @return
     */
    @ApiOperation(value = "分页查询,startDate 格式：yyyy-MM-dd, endDate 格式： yyyy-MM-dd", notes = "分页查询")
    @GetMapping("/page" )
    public R getSwCkClearDetailPage(Page page,String lineCode, String startDate, String endDate) {
        SwCkClearDetail swCkClearDetail = new SwCkClearDetail();
        swCkClearDetail.setLineCode(lineCode);
        if(StringUtils.isNotEmpty(startDate)) {
            swCkClearDetail.setBeginTime(LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        if(StringUtils.isNotEmpty(endDate)) {
            swCkClearDetail.setEndTime(LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }

        return R.ok(swCkClearDetailService.page(page, Wrappers.query(swCkClearDetail).orderByDesc("BEGIN_TIME")));
    }

    /**
     * 清分及划账-清分及划账记录-系统自动清分
     * @return R
     */
    @ApiOperation(value = "清分及划账-清分及划账记录-正常清分数据-系统自动清分，点击“系统自动清分”按钮弹出窗口选择时间段(二者必须选)", notes = "清分及划账-清分及划账记录-正常清分数据-系统自动清分，点击“系统自动清分”按钮弹出窗口选择时间段(二者必须选)")
    @SysLog("清分及划账-清分及划账记录-正常清分数据-系统自动清分" )
    @GetMapping({"/autoClean"})
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_detail_autoClean')" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期", dataTypeClass = String.class, required = true),
                    @ApiImplicitParam(name = "endDate", value = "结束日期", dataTypeClass = String.class, required = true)
            }
    )
    public R autoClean(String startDate, String endDate) {
        try {
            if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)){
                return R.failed();
            }
            Map<String,String> mapLineClearRule = swCkClearRuleService.selectRulesDetailsMapByDate(startDate, endDate);
            if(mapLineClearRule.size() == 0){
                return R.failed("日期范围内没有清分规则！");
            }      

			String ruleKey = SwCkClearRuleConstans.CLEAR_RULE_MANMADE+","+"1,1,1";
            if(mapLineClearRule.size()> 0 && ObjectUtil.isEmpty(mapLineClearRule.get(ruleKey))){
                return R.failed("日期范围内没有关于人工协议线路清分规则！");
            }			
			
            return R.ok(swCkClearDetailService.generateSwCkClearDetail(startDate, endDate));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed();
        }

    }
    /**
     * 判断是否存在已经清分的记录
     * @param startDate
     * @param endDate
     * @return
     */
    //判断是否存在已经清分的记录
	//前台验证，如果存在，提示为“该日期范围内已经做过清分，是否再次重新清分”
    @ApiOperation(value = "判断是否存在已经清分的记录", notes = "判断是否存在已经清分的记录")
    @GetMapping({"/isReClean"})
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期", dataTypeClass = String.class, required = true),
                    @ApiImplicitParam(name = "endDate", value = "结束日期", dataTypeClass = String.class, required = true)
            }
    )
	public R isExistClean(String startDate,String endDate){
	       
			SwCkClearDetail swCkClearDetail = new SwCkClearDetail();           
            swCkClearDetail.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            swCkClearDetail.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            QueryWrapper<SwCkClearDetail> queryDetail = Wrappers.query(swCkClearDetail);
            List<SwCkClearDetail> ClearDetail = swCkClearDetailService.list(queryDetail);
            return R.ok(ClearDetail);
	}

    /**
     * 清分及划账-清分及划账记录-重新清分
     * @return R
     */
    @ApiOperation(value = "清分及划账-清分及划账记录-正常清分数据-重新清分，必须选择左边复选框，可多选", notes = "清分及划账-清分及划账记录-正常清分数据-重新清分，必须选择左边复选框，可多选")
    @SysLog("清分及划账-清分及划账记录-正常清分数据-重新清分" )
    @GetMapping({"/reClean"})
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_detail_reClean')" )
    public R reClean(@RequestParam(value = "ids") List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()){
                return R.failed();
            }
            return R.ok(swCkClearDetailService.reGenerateSwCkClearDetail(ids));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed();
        }

    }

    /**
     * 清分及划账-清分及划账记录-生成财务报表
     * @return R
     */
    @ApiOperation(value = "清分及划账-清分及划账记录-正常清分数据-生成财务报表，点击“系统自动清分”按钮弹出窗口选择时间段(二者必须选)", notes = "清分及划账-清分及划账记录-正常清分数据-生成财务报表，点击“系统自动清分”按钮弹出窗口选择时间段(二者必须选)")
    @SysLog("清分及划账-清分及划账记录-正常清分数据-生成财务报表" )
    @GetMapping({"/genReport"})
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_detail_genReport')" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期", dataTypeClass = String.class, required = true),
                    @ApiImplicitParam(name = "endDate", value = "结束日期", dataTypeClass = String.class, required = true)
            }
    )
    public R genReport(String startDate, String endDate) {
        try {
            if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)){
                return R.failed();
            }

            return R.ok(swCkClearDetailService.genReport(startDate, endDate));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed();
        }

    }
	 /**
     * 清分及划账-清分及划账记录-特殊票种系统自动清分
     * @return R
     */
    @ApiOperation(value = "清分及划账-清分及划账记录-正常清分数据-特殊票种系统自动清分，点击“系统自动清分”按钮弹出窗口选择时间段(二者必须选)", notes = "清分及划账-清分及划账记录-正常清分数据-特殊票种系统自动清分，点击“系统自动清分”按钮弹出窗口选择时间段(二者必须选)")
    @SysLog("清分及划账-清分及划账记录-正常清分数据-系统自动清分" )
    @GetMapping({"/autoCleanSpecialTicket"})
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "日期，yyyy-MM格式", dataTypeClass = String.class, required = true), 
                    @ApiImplicitParam(name = "clearRule", value = "清分规则 7：日票   8:纪念票", dataTypeClass = String.class, required = true)  
            }
    )
    public R autoCleanSpecialTicket(String startDate,String clearRule) {
        try {
            if (StringUtils.isEmpty(startDate)){
                return R.failed();
            }
            int iYear = Integer.parseInt(startDate.split("-")[0]);
            int iMonth = Integer.parseInt(startDate.split("-")[1]);
            String realStartDate = MyDateUtil.getFirstDayOfMonth(iYear, iMonth);
            String realEndDate = MyDateUtil.getLastDayOfMonth(iYear, iMonth);
            Map<String,String> mapLineClearRule = swCkClearRuleService.selectRulesDetailsMapByDate(realStartDate, realEndDate) ;
            if(mapLineClearRule.size()== 0){
                return R.failed("日期范围内没有清分规则！");
            }
            String ruleKeyDaily = SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET+","+"1"+","+SwCkClearRuleConstans.SERVICE_ID_XADT+",1";
            String ruleKeySunivenir = SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET+","+"1"+","+SwCkClearRuleConstans.SERVICE_ID_XADT+",1";
            if(mapLineClearRule.size()> 0 && ObjectUtil.isEmpty(mapLineClearRule.get(ruleKeyDaily))){
                return R.failed("日期范围内没有日票的清分规则！");
            }
            if(mapLineClearRule.size()> 0 && ObjectUtil.isEmpty(mapLineClearRule.get(ruleKeySunivenir))){
                return R.failed("日期范围内没有纪念票的清分规则！");
            }
            List<String> lstClearRules = new ArrayList();
            lstClearRules.add(clearRule);
            return R.ok(swCkClearDetailService.generateSpecialTicketsSwCkClearDetail(realStartDate, realEndDate,lstClearRules));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed();
        }

    }

	 /**
     * 清分及划账-清分及划账记录-系统按月生成报表
     * @return R
     */
    @ApiOperation(value = "清分及划账-清分及划账记录-系统按月生成报表，点击“系统按月生成报表”按钮弹出窗口选择时间(yyyy-MM格式)", notes = "清分及划账-清分及划账记录-系统按月生成报表，点击“系统按月生成报表”按钮弹出窗口选择时间(yyyy-MM格式)")
    @SysLog("清分及划账-清分规则管理-系统自动计算按月" )
    @GetMapping({"/autoClearMonth"})
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "日期 yyyy-MM格式", dataTypeClass = String.class, required = true)                  
            }
    )    
    public R autoClearMonth(String startDate) {
        try {
            if (StringUtils.isEmpty(startDate)){
                return R.failed();
            }
            int iYear = Integer.parseInt(startDate.split("-")[0]);
            int iMonth = Integer.parseInt(startDate.split("-")[1]);
            String realStartDate = MyDateUtil.getFirstDayOfMonth(iYear, iMonth);
            String realEndDate = MyDateUtil.getLastDayOfMonth(iYear, iMonth);
            return R.ok(swCkClearDetailService.autoClearMonth(realStartDate, realEndDate));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed();
        }

    }

}
